#!/usr/bin/env ruby

# To be run against files in this bundle to remove any
# non-OS agnostic characters (see BADCHARS list)
# AIM: ease the pain of access to this bundle by WinOS
# machines, for E Text Editor etc.

require 'uri'
require 'find'
require 'fileutils'
include FileUtils::Verbose

DIR_TO_CLEAN = File.expand_path(File.dirname(__FILE__) + "/../")
BADCHARS = /([<>\|:\*…\"\?\\“”↵—↓↵‘’¬])/

def sanitize(f)
	URI.escape(f, BADCHARS).chomp
end

def verbose_rename (orig_name, new_name)
  File.rename(orig_name, new_name)
  puts orig_name + " --> " + new_name
end

# Sanitize the transit dir
bad_dirs = []
Find.find(DIR_TO_CLEAN) do |f|
  f = File.expand_path(f).sub(DIR_TO_CLEAN, '')
  next if f =~ /\/?\.(git|svn)/
  orig_name = File.basename(f)
  next if orig_name === ( clean_name = sanitize(File.basename(f)) )
  if File.directory? f
		bad_dirs.push(f)
		next
	end
  dirname = File.dirname(f) + "/"
  verbose_rename(dirname + orig_name, dirname + clean_name) unless (orig_name === clean_name)
end

puts "Renaming #{bad_dirs.size} dirs..."
bad_dirs.each do |d|
	orig_name = File.basename(d)
	clean_name = sanitize(File.basename(d))
	dirname = File.dirname(d) + "/"
	verbose_rename(dirname + orig_name, dirname + clean_name)
end
